#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Time    : 2019/10/31 17:15
# Author  : simple0426
# Email   : istyle.simple@gmail.com
# File    : rabbitmq_pika_producer.py
# Software: PyCharm
import pika, sys

# 建立链接
auth = pika.credentials.PlainCredentials('ever01', 'Theistyle')
# 连接单个mq实例
# conn_para = pika.ConnectionParameters(
#     host='127.0.0.1',
#     port=5672,
#     virtual_host='celery',
#     credentials=auth
# )

# 连接多个mq实例
conn_para = (
    pika.ConnectionParameters(
        host='192.168.31.231',
        port=5672,
        virtual_host='celery',
        credentials=auth,
        connection_attempts=3,
        retry_delay=1
    ),
    pika.ConnectionParameters(
        host='192.168.31.232',
        port=5672,
        virtual_host='celery',
        credentials=auth,
        connection_attempts=3,
        retry_delay=1
    ),
    pika.ConnectionParameters(
        host='192.168.31.233',
        port=5672,
        virtual_host='celery',
        credentials=auth,
        connection_attempts=3,
        retry_delay=1
    ),
)
conn = pika.BlockingConnection(parameters=conn_para)

# 创建channel
channel = conn.channel()
# direct模式
# channel.exchange_declare( # 创建exchange
#     exchange='direct_log',
#     exchange_type='direct',
#     durable=True)
# topic模式
# channel.exchange_declare( # 创建exchange
#     exchange='topic_log',
#     exchange_type='topic',
#     durable=True)
channel.exchange_declare( # 创建exchange
    exchange='fanout_log',
    exchange_type='fanout',
    durable=True)

# 定义发送的key和内容
keys = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info' # 定义key
message = ''.join(sys.argv[2:]) or 'Hello World!' # 定义message

# 发布消息
channel.basic_publish(
    # exchange='direct_log',
    # exchange='topic_log',
    exchange='fanout_log',
    routing_key=keys,
    body=message,
    properties=pika.BasicProperties(delivery_mode=2)
)
print("[x] Sent %r:%r" % (keys, message))
conn.close()
